package com.hnkywl.sts.webservice.wly.impl;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hnkywl.sts.dao.sys.GgDao;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.sys.Gg;
import com.hnkywl.sts.entity.xsgl.Kh;
import com.hnkywl.sts.entity.xsgl.Xsd;
import com.hnkywl.sts.entity.xsgl.Xsmx;
import com.hnkywl.sts.service.base.WebserviceLogService;
import com.hnkywl.sts.service.kcgl.CkshService;
import com.hnkywl.sts.service.kcgl.SskcService;
import com.hnkywl.sts.service.sys.WzbmService;
import com.hnkywl.sts.service.xsgl.KhService;
import com.hnkywl.sts.service.xsgl.XsdService;
import com.hnkywl.sts.webservice.wly.IMeasureCountFeedBack;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by Jerry on 14-1-2.
 * 接收实体量回传信息
 */
@Service
public class MeasureCountFeedBackService implements IMeasureCountFeedBack, ApplicationContextAware {
    private ApplicationContext applicationContext;

    private XsdService xsdService;
    private CkshService ckshService;
    private SskcService sskcService;
    private GgDao ggDao;
    private WebserviceLogService webserviceLogService;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
        xsdService = (XsdService) applicationContext.getBean("xsdService");
        ckshService = (CkshService) applicationContext.getBean("ckshService");
        sskcService = (SskcService) applicationContext.getBean("sskcService");
        ggDao = (GgDao) applicationContext.getBean("ggDao");
        webserviceLogService = (WebserviceLogService) applicationContext.getBean("webserviceLogService");
    }

    @Override
    public String measureCountFeedBackResponse(String json) {
        String result = "";
        String exception = null;
        try {
            this.checkXsdJson(json);//先校验通过
            //根据实提量填写实体量更改状态
            Map<String, String> map = updateXsdFromJson(json);
            if (null != map) {
                String[] arrSBillcodes = map.get("scontractBillcodes").split(",");
                String[] rnss = map.get("rsns").split(",");
                result += "[";
                for (int i = 0; i < rnss.length; i++) {
                    String scb = arrSBillcodes[i];
                    String rns = rnss[i];
                    if (StringUtils.isNotEmpty(scb) && StringUtils.isNotEmpty(rns)) {
                        result += "{\"flag\":\"0\",\"resource_serial_number_1\":\"" + rns + "\",\"billCode\":\"" + scb + "\",\"msg\":\"实提量反馈成功!\"}" + ",";

                    }
                }
            }
            result = result.substring(0, result.length() - 1) + "]";
        } catch (Exception e) {
            exception = e.getMessage();
            result = "[{\"flag\":\"1\",\"billCode\":\" \",\"msg\":\"数据异常:" + e.getMessage() + "\"}]";
        }
        webserviceLogService.saveServerLog(
                AccountBalanceService.class.getName(),
                "putStorageFeedback",
                json,
                "返回结果：" + result,
                exception,
                ""
        );
        return result;
    }

    //校验json
    public void checkXsdJson(String json) throws RuntimeException {
        Gson gson = new Gson();
        if (json == null || "".equals(json)) {
            throw new RuntimeException("json为空!");
        }
        List<Map<String, String>> resultMapList = gson.fromJson(json, new TypeToken<ArrayList<Map<String, String>>>() {
        }.getType());
        if (null != resultMapList && resultMapList.size() > 0) {
            for (Map<String, String> resultMap : resultMapList) {
                if (resultMap.isEmpty()) {
                    throw new RuntimeException("传入内容为空!");
                }
                String xsdh = resultMap.get("scontractBillcode");//出库单号
                if (xsdh == null || "".equals(xsdh)) {
                    throw new RuntimeException("scontractBillcode为空!");
                }
                String billBillcode = resultMap.get("billBillcode");//提单号
                if (billBillcode == null || "".equals(billBillcode)) {
                    throw new RuntimeException("billBillcode为空!");
                }
//                String name = resultMap.get("name");//品名
//                if (name == null || "".equals(name)) {
//                    throw new RuntimeException("name为空!scontractBillcode=" + xsdh);
//                }
//                String cz = resultMap.get("quality");//材质
//                if (cz == null || "".equals(cz)) {
//                    throw new RuntimeException("quality为空!scontractBillcode=" + xsdh);
//                }
//                String ggxh = resultMap.get("standardModel");//规格型号
//                if (ggxh == null || "".equals(ggxh)) {
//                    throw new RuntimeException("standard为空!scontractBillcode=" + xsdh);
//                }

                String rsn = resultMap.get("resource_serial_number_1");// 仓储资源唯一号
                if (rsn == null || "".equals(rsn)) {
                    throw new RuntimeException("resource_serial_number_1为空!scontractBillcode=" + xsdh);
                }
                String ck = resultMap.get("warehouse");//仓库
                if (ck == null || "".equals(ck)) {
                    throw new RuntimeException("warehouse为空!scontractBillcode=" + xsdh);
                }
                String weight = resultMap.get("weight");//重量
                if (weight == null || "".equals(weight)) {
                    throw new RuntimeException("weight为空!scontractBillcode=" + xsdh);
                }
            }
        }
    }


    private synchronized Map<String, String> updateXsdFromJson(String json) throws RuntimeException {
        Gson gson = new Gson();
        Map<String, String> map = new HashMap<String, String>();
        String scontractBillcodes = "";
        String rsns = "";
        List<Map<String, String>> resultMapList = gson.fromJson(json, new TypeToken<ArrayList<Map<String, String>>>() {
        }.getType());
        if (null != resultMapList && resultMapList.size() > 0) {
            for (Map<String, String> resultMap : resultMapList) {
                String scontractBillcode = resultMap.get("scontractBillcode");//销售单号
                scontractBillcodes += scontractBillcode + ",";
                Xsd xsd = this.xsdService.findByXsdh(scontractBillcode);
                String number = resultMap.get("number") == null ? "0" : resultMap.get("number");//件数
                Double weight = Double.valueOf(resultMap.get("weight"));//重量
                String rsn = resultMap.get("resource_serial_number_1");// 仓储资源唯一号
                Kh kh = this.sskcService.checkExist(rsn);
                if (kh != null) {
                    Gg gg = kh.getJtwz();
                    rsns += rsn + ",";
                    Xsmx xsmx = this.xsdService.findXsmxByJtwz(xsd, kh);
                    xsmx.setCk_js(Integer.parseInt(number));
                    xsmx.setCk_sbsl(weight);
                    xsmx.setKh(kh);
                    xsmx.setXsd(xsd);
                    this.xsdService.saveXsmx(xsmx);
                    Boolean flag = false;
                    for (Xsmx xsdmx : xsd.getXsmxList()) {
                        if (xsdmx.getCk_sbsl() == null) {
                            flag = true;
                            break;
                        }
                    }
                    if (!flag) {
                        ckshService.checkCksh(xsd);
                        //判断是自提还是过户，过户不需要做出库操作
//            if (deliveryType.equals("transfer")) {
//                ckshService.checkCksh(xsd);
//            } else if (deliveryType.equals("self")) {
//                xsd.setZt("ysp");
//                xsd.setCwsh(true);
//                xsd.setYck(true);
//                xsd.setCkshbz(true);
//                xsd.setCksj(new Date());
//                this.xsdService.editXsd(xsd, xsd.getXsdh());
//            }
                    }
                }
            }
        }
        map.put("scontractBillcodes", scontractBillcodes);
        map.put("rsns", rsns);
        return map;
    }
}
